import axios from 'axios'
import cookie from 'js-cookie'
import { Message } from 'element-ui'
// 创建axios实例
const service = axios.create({
    baseURL: 'http://127.0.0.1:30010/services',
    timeout: 6000 // 请求超时时间
})
// http request 拦截器
service.interceptors.request.use(
    config => {
    //判断cookie中是否有值
    if(cookie.get('token')){
        //将cookie中token的值放到headers中
        config.headers['token'] = cookie.get('token')
    }
    return config
},
    err => {
    return Promise.reject(err)
})
// http response 拦截器
service.interceptors.response.use(
    response => {
        //根据状态码code判断是否登录
        if(response.data.code === 208){
            //208表示未登录，弹出登录框，或者token过期了
            window.alert("token失效请重新登录！")
            return
        }else{
            if (response.data.code !== 200) {
            Message({
                message: response.data.message,
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(response)
            } else {
                return response
            }
        }
    },
    error => {
        return Promise.reject(error.response)
})
export default service

